package net.maku.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import net.maku.bean.model.MyException;

import java.util.Base64;

public class WeChatDecrypt {
	public static String decrypt(String encryptedData, String sessionKey, String iv)  {
	    // Base64 解码
		try {
		    byte[] decodedData = Base64.getDecoder().decode(encryptedData);
		    byte[] key = Base64.getDecoder().decode(sessionKey);
		    byte[] ivBytes = Base64.getDecoder().decode(iv);
		    
		    // 使用 AES/CBC/PKCS5Padding 加密方式
		    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
		    
		    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		    
		    // 解密数据
		    byte[] decrypted = cipher.doFinal(decodedData);
		    return new String(decrypted, "UTF-8");
		}catch(Exception ex) {
			throw new MyException(ex.getMessage());
		}
	}
}
